package com.text;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.QName;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.util.StringUtil;

public class Test123 {
	
	private static List<String> list=new ArrayList<String>();
	
	public String convertStringToHex(String str) {

		char[] chars = str.toCharArray();

		StringBuffer hex = new StringBuffer();
		for (int i = 0; i < chars.length; i++) {
			hex.append(Integer.toHexString((int) chars[i]));
		}

		return hex.toString();
	}

	public String convertHexToString(String hex) {

		StringBuilder sb = new StringBuilder();
		StringBuilder temp = new StringBuilder();

		// 49204c6f7665204a617661 split into two characters 49, 20, 4c...
		for (int i = 0; i < hex.length() - 1; i += 2) {

			// grab the hex in pairs
			String output = hex.substring(i, (i + 2));
			// convert hex to decimal
			int decimal = Integer.parseInt(output, 16);
			// convert the decimal to character
			sb.append((char) decimal);

			temp.append(decimal);
		}

		return sb.toString();
	}

	// 504F533838383834 POS88884
	public static void main(String[] args) throws FileNotFoundException {
		/* CompilationUnit cu = JavaParser.parse(new FileInputStream("D:/SourceCode/workspace2/CodeGenerationMvn/src/main/java/com/text/Test123.java"));

	        Optional<ClassOrInterfaceDeclaration> classByName = cu.getClassByName("Test123");
	        ClassOrInterfaceDeclaration orElse = classByName.orElse(null);
	        //参数添加
	        FieldDeclaration field = orElse.addField(String.class, "sssss=\"ddd\"",Modifier.PUBLIC,Modifier.STATIC);
	        field.setBlockComment("添加参数备注"); //添加参数备注
	        field.addMarkerAnnotation("RestController");//添加头部注解如:@RestController
	        //普通方法添加
	        MethodDeclaration addMethod = orElse.addMethod("setSssss", Modifier.PUBLIC,Modifier.STATIC);
	        addMethod.addParameter(String.class, "s");//添加入参
	        addMethod.setType(String.class); //添加返回类型
	        addMethod.setBlockComment("添加备注"); //添加备注
	        addMethod.addMarkerAnnotation("RestController");//添加头部注解如:@RestController
			BlockStmt body=new BlockStmt();
			body.addStatement("s+=\"kkk\";"); //添加java语句
			body.addStatement("return s;");  //添加java语句
			addMethod.setBody(body);
			//接口方法添加
			MethodDeclaration addMethod1 = orElse.addMethod("setSssss1", Modifier.PUBLIC,Modifier.STATIC);
			addMethod1.addParameter(String.class, "s");//添加入参
	        addMethod1.setType(String.class); //添加返回类型
	        addMethod1.setBlockComment("添加备注"); //添加备注
	        addMethod1.removeBody();
	        System.out.println(orElse);
	        System.out.println(cu.toString());*/
	       /* File file = new File("C:/Users/ydyt02/git/crm-service/workflow-service/src/main/resources/diagrams/dl/cooperate_business_contract_checkV2.bpmn");
	        Document document = getDocument(file);*/
	        Document document = DocumentHelper.createDocument();   
	        gerAll(document,3);
	}
	
	public static Document getDocument(File file){

        //创建一个XML解析器
        SAXReader saxReader = new SAXReader();
        try {
            //读取Document对象
            Document document = null;
            document = saxReader.read(file);
            return document;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }
	
	/**
     * 遍历所有的标签节点
     * @param document
     */
    public static void gerAll(Document document,Integer taskSize){
        Element root = document.addElement("definitions");// 创建根节点
        root.addAttribute("xmlns", "http://www.omg.org/spec/BPMN/20100524/MODEL");
        root.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        root.addAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
        root.addAttribute("xmlns:activiti", "http://activiti.org/bpmn");
        root.addAttribute("xmlns:bpmndi", "http://www.omg.org/spec/BPMN/20100524/DI");
        root.addAttribute("xmlns:omgdc", "http://www.omg.org/spec/DD/20100524/DC");
        root.addAttribute("xmlns:omgdi", "http://www.omg.org/spec/DD/20100524/DI");
        root.addAttribute("xmlns:tns", "http://www.activiti.org/test");
        root.addAttribute("typeLanguage", "http://www.w3.org/2001/XMLSchema");
        root.addAttribute("expressionLanguage", "http://www.w3.org/1999/XPath");
        root.addAttribute("targetNamespace", "http://www.activiti.org/test");
        root.addAttribute("id", "m1500975248354");
        root.addAttribute("name", "");
        //流程定义
        Element process = root.addElement("process");
        process.addAttribute("id","sale_price_approval_process"); //流程定义key
        process.addAttribute("name","联合办公订单审核流程" ); //流程名称
        process.addAttribute("isExecutable","true" );
        process.addAttribute("isClosed","false" );
        process.addAttribute("processType","None");
        Element documentation = process.addElement("documentation");
        documentation.addText("cooperateBusinessOrderProcess");
        //样式定义
        Element diagram =root.addElement("bpmndi");
        diagram.setName("bpmndi:BPMNDiagram");
        diagram.addAttribute("id", "BPMNDiagram_sale_price_approval_process");
        Element plane = diagram.addElement("bpmndi");
        plane.setName("bpmndi:BPMNPlane");
        plane.addAttribute("bpmnElement", "sale_price_approval_process");
        plane.addAttribute("id", "BPMNPlane_sale_price_approval_process");
        
        //流程添加节点
        Element startEvent = process.addElement("startEvent");
        startEvent.addAttribute("id", "startevent");
        startEvent.addAttribute("name", "Start");
        int flowNum=0;
        for (int i = 0; i < taskSize; i++) {
        	Element userTask = process.addElement("userTask");
        	userTask.addAttribute("id","sale_price_approval_check"+i);
        	userTask.addAttribute("activiti:formKey","salePriceApprovalCheck"+i);
        	if(i==0){
        		userTask.addAttribute("name","提交审核"); 
        		userTask.addAttribute("activiti:assignee","${applicant}"); 
        	}else{
        		userTask.addAttribute("name","节点"+i); 
        		userTask.addAttribute("activiti:assignee",""); 
        	}
        	Element utDoc = userTask.addElement("documentation");
        	utDoc.addText("{\"businessType\":\"salePriceApprovalCheck"+i+"\",\"departmentCode\":\"100003\",\"gatewayName\":\"gateWay1\"}");
        	Element extensionElements = userTask.addElement("extensionElements");
        	Element activiti = extensionElements.addElement("activiti");
        	activiti.setName("activiti:taskListener");
        	activiti.addAttribute("event", "create");
        	activiti.addAttribute("class", "com.yst.workflow.task.listener.GlobalListenerImpl");
		}
        Map<String,Object> map=new HashMap<String,Object>();
        Element one = process.addElement("sequenceFlow");
        map.put("flow"+flowNum, "sale_price_approval_check"+0);
        one.addAttribute("id","flow"+(flowNum++));
        one.addAttribute("targetRef","sale_price_approval_check"+0);
        one.addAttribute("sourceRef","startevent");
        Element endEvent = process.addElement("endEvent");
        endEvent.addAttribute("id", "endevent");
        endEvent.addAttribute("name", "End");
        for (int i = 0; i < taskSize; i++) {
        	Element sequenceFlow = process.addElement("sequenceFlow");
        	sequenceFlow.addAttribute("id","flow"+(flowNum++));
        	sequenceFlow.addAttribute("sourceRef","sale_price_approval_check"+i);
        	sequenceFlow.addAttribute("targetRef","exclusivegateway"+i);
        	Element exclusiveGateway = process.addElement("exclusiveGateway");
        	exclusiveGateway.addAttribute("id","exclusivegateway"+i);
        	exclusiveGateway.addAttribute("name","网关"+i);
        	exclusiveGateway.addAttribute("default","flow"+(flowNum++));
        	if(i==0){
        		Element sequenceFlow1 = process.addElement("sequenceFlow");
        		sequenceFlow1.addAttribute("id","flow"+(flowNum-1));
        		sequenceFlow1.addAttribute("name","撤销");
        		sequenceFlow1.addAttribute("sourceRef","exclusivegateway"+i);
        		sequenceFlow1.addAttribute("targetRef","endevent");
        	}else{
        		Element sequenceFlow1 = process.addElement("sequenceFlow");
        		map.put("flow"+flowNum, "sale_price_approval_check"+0);
        		sequenceFlow1.addAttribute("id","flow"+(flowNum-1));
        		sequenceFlow1.addAttribute("name","驳回");
        		sequenceFlow1.addAttribute("sourceRef","exclusivegateway"+i);
        		sequenceFlow1.addAttribute("targetRef","sale_price_approval_check"+0);
        	}
        	
        	Element sequenceFlow1 = process.addElement("sequenceFlow");
    		sequenceFlow1.addAttribute("id","flow"+(flowNum++));
    		sequenceFlow1.addAttribute("name","同意");
    		sequenceFlow1.addAttribute("sourceRef","exclusivegateway"+i);
    		Element conditionExpression = sequenceFlow1.addElement("conditionExpression");
    		conditionExpression.addAttribute("xsi:type","tFormalExpression");
    		conditionExpression.addAttribute("name","同意");
    		conditionExpression.addAttribute("sourceRef","exclusivegateway"+i);
    		if(i==0){
    			conditionExpression.addText("<![CDATA[${cancel==false}]]>");
    		}else{
    			conditionExpression.addText("<![CDATA[${salePriceApprovalCheck"+i+"IsApprove==1}]]>");
    		}
        	if(i==(taskSize-1)){
        		sequenceFlow1.addAttribute("targetRef","endevent");
        	}else{
        		map.put("flow"+(flowNum-1), "sale_price_approval_check"+(i+1));
        		sequenceFlow1.addAttribute("targetRef","sale_price_approval_check"+(i+1));
        	}
        	
        }
        
        Element shape = plane.addElement("bpmndi");
        shape.setName("bpmndi:BPMNShape");
        shape.addAttribute("bpmnElement", "startevent");
        shape.addAttribute("id", "BPMNShape_startevent");
        Element bounds = shape.addElement("omgdc");
        bounds.setName("omgdc:Bounds");
        bounds.addAttribute("height", "35.0");
        bounds.addAttribute("width", "35.0");
        bounds.addAttribute("x", "23.0");
        bounds.addAttribute("y", ""+(23.0+(137*(taskSize-1))));
        for (int i = 0; i < taskSize; i++) {
        	//节点
        	Element shape1 = plane.addElement("bpmndi");
        	shape1.setName("bpmndi:BPMNShape");
            shape1.addAttribute("bpmnElement", "sale_price_approval_check"+i);
            shape1.addAttribute("id", "BPMNShape_sale_price_approval_check"+i);
            Element bounds1 = shape1.addElement("omgdc");
            bounds.setName("omgdc:Bounds");
            bounds1.addAttribute("height", "60.0");
            bounds1.addAttribute("width", "100.0");
            if(i==0){
            	if(map.containsValue("sale_price_approval_check"+i)){
            		Map<String,Object> di=new HashMap<String, Object>();
            		di.put("x",  "100.0");
            		di.put("y", ""+(23.0+(137*(taskSize-1))));
            		map.put("sale_price_approval_check"+i, di);
            	}
            	 bounds1.addAttribute("x", "100.0");
                 bounds1.addAttribute("y", ""+(23.0+(137*(taskSize-1))));
            }else{
            	if(map.containsValue("sale_price_approval_check"+i)){
            		Map<String,Object> di=new HashMap<String, Object>();
            		di.put("x", ""+(320.0+(250*i)));
            		di.put("y", ""+(100.0+(250*i)));
            		map.put("sale_price_approval_check"+i, di);
            	}
            	 bounds1.addAttribute("x", ""+(320.0+(250*i)));
                 bounds1.addAttribute("y", ""+(100.0+(250*i)));
            }
            //网关
            Element shape2 = plane.addElement("bpmndi");
            shape2.setName("bpmndi:BPMNShape");
            shape2.addAttribute("bpmnElement", "exclusivegateway"+i);
            shape2.addAttribute("id", "BPMNShape_exclusivegateway"+i);
            Element bounds2 = shape2.addElement("omgdc");
            bounds2.setName("omgdc:Bounds");
            bounds2.addAttribute("height", "40.0");
            bounds2.addAttribute("width", "40.0");
            bounds2.addAttribute("x", ""+(220.0+(250*i)));
            bounds2.addAttribute("y", ""+(23.0+(137*i)));
        }
        
        for (int i = 0; i < flowNum; i++) {
        	Element shape2 = plane.addElement("bpmndi");
            shape2.setName("bpmndi:BPMNEdge");
            shape2.addAttribute("bpmnElement", "flow"+i);
            shape2.addAttribute("id", "BPMNEdge_flow"+i);
            Element omgdi = shape2.addElement("omgdi");
            omgdi.setName("omgdi:waypoint");
            omgdi.addAttribute("x", ""+(220.0+(1*i)));
            omgdi.addAttribute("y", ""+(23.0+(1*i)));
            
           
            if(map.containsKey("flow"+i)){
            	Element bpmndiLabel = shape2.addElement("bpmndi");
            	bpmndiLabel.setName("bpmndi:BPMNLabel");
        		String string = map.get("flow"+i).toString();
        		Map<String,Object> di= (Map<String, Object>) map.get(string);
        		if(di!=null){
        			Element omgdc1 = bpmndiLabel.addElement("omgdc");
            		omgdc1.setName("omgdc:Bounds");
            		omgdc1.addAttribute("height", "14.0");
            		omgdc1.addAttribute("width", "100.0");
            		omgdc1.addAttribute("x", di.get("x").toString());
            		omgdc1.addAttribute("y", di.get("y").toString());
        		}
            }
		}
    	
        try {
			writeXml(document);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    /**
     * 把修改后的Document对象写出到xml文档中
     * @param document
     * @throws IOException
     */
    public static void writeXml(Document document) throws IOException {
        //把修改后的Document对象写出到xml文档中
        FileOutputStream out = new FileOutputStream("D:/亿达文件/代码生成配置/userWrite1.bpmn");
        //比较美观的排版方式 用于人阅读
        OutputFormat format = OutputFormat.createPrettyPrint();

        //紧凑型的排版方式 ，主要用于程序运行中使用 减少不必要的空格换行等
        //OutputFormat format2 = OutputFormat.createCompactFormat();

        format.setEncoding("utf-8");
        XMLWriter writer = new XMLWriter(out,format);
        writer.write(document);
        writer.close();
    }

    
	
	protected static String warpProcessTaskComment(Boolean approveFlag, String comment) {
		StringBuilder sb = new StringBuilder();
		if (approveFlag) {
			sb.append("审核通过");
		} else {
			sb.append("审核驳回");
		}
		if (comment==null) {
			sb.append("：").append(comment);
		}
		return sb.toString();
	}
}
